package com.googlecode.marrowboy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Central class which controls all non-assertion access
 * 
 * @author mjg
 */
public class MarrowBoy {

    public static final String OUT_DIR_SYSTEM_PROPERTY_NAME = "marrowboy.report.dir";
    public static final String OUT_FILES_SYSTEM_PROPERTY_NAME = "marrowboy.report.files";

    public static final String DEFAULT_OUTPUT_FILE = "marrowboy-report.html";
    
    public static TestLogger testLogger;

    static {
        initialiseTestLogger();
        addOutputShutdownHook();
    }

    private static void initialiseTestLogger() {
        File outputDir = createOutputDirectory();
        List<File> outputFiles = createOutputFiles(outputDir);
        testLogger = new TestLogger(outputFiles);
    }

    private static List<File> createOutputFiles(File outputDir) {
        String[] outFileNames = getOutputFileNames();
        
        List<File> files = new ArrayList<File>();
        for(String thisFileName: outFileNames){
            files.add(new File(outputDir, thisFileName));
        }
        
        return files;
    }

    private static String[] getOutputFileNames() {
        String outputFiles = System.getProperty(OUT_FILES_SYSTEM_PROPERTY_NAME, DEFAULT_OUTPUT_FILE);
        return outputFiles.split(",\\s*");
    }

    private static File createOutputDirectory() {
        String outputDirName = System.getProperty(OUT_DIR_SYSTEM_PROPERTY_NAME, getDefaultOutputDir());
        File outputDir = new File(outputDirName);
        outputDir.mkdirs();
        return outputDir;
    }

    private static String getDefaultOutputDir() {
        if (runningThroughMaven()){
            return "target";
        } else {
            return ".";
        }
        
    }

    private static boolean runningThroughMaven() {
        // TODO: Check that this works as expected.
        return System.getProperty("localRepository") != null;
    }

    private static void addOutputShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                testLogger.writeAllOutputs();
            }
        });
    }

    public static TestLogger getTestLogger() {
        return testLogger;
    }

}
